package cn.com.cifi.mars.service.impl;

import cn.com.cifi.mars.bean.dto.SysPermissionDto;
import cn.com.cifi.mars.bean.vo.sys.req.EnableSysPermissionReqParam;
import cn.com.cifi.mars.bean.vo.sys.req.SaveSysPermissionReqParam;
import cn.com.cifi.mars.bean.vo.sys.req.UpdateSysPermissionReqParam;
import cn.com.cifi.mars.common.exception.MsgException;
import cn.com.cifi.mars.constant.CodeEnum;
import cn.com.cifi.mars.constant.Constants;
import cn.com.cifi.mars.constant.IsDisableEnum;
import cn.com.cifi.mars.entity.common.IdmOrg;
import cn.com.cifi.mars.entity.common.SysPermission;
import cn.com.cifi.mars.mapper.mars.SysPermissionMapper;
import cn.com.cifi.mars.service.SysPermissionService;
import cn.com.cifi.mars.util.UUIDUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 权限表 服务实现类
 * </p>
 *
 * @author yyd
 * @since 2019-09-18
 */
@Service
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission> implements SysPermissionService {

	@Autowired
	private SysPermissionMapper sysPermissionMapper;

	/**
	 * 添加权限
	 */
	@Transactional
	@Override
	public int add(SaveSysPermissionReqParam param,String name) {
		int count=sysPermissionMapper.selectByPerCode( param.getPerCode());
		if(count>0) {
			throw new MsgException(CodeEnum.SYS_PERMISSION_CODE_ERROR);
		}
		msgException(param.getPerCode(),param.getPerName(),param.getPerType(),param.getItsApplicationCode(),param.getSort()) ;
		SysPermission bean=new SysPermission();
		BeanUtils.copyProperties(param, bean);
		bean.setCreateby(name);
		bean.setCreateTime(LocalDateTime.now());
		bean.setIsVaild(IsDisableEnum.NO.getKey()+"");
		bean.setSort(Integer.parseInt(param.getSort()));
		bean.setId(UUIDUtils.create());
		int num=sysPermissionMapper.insert(bean);
		return num;
	}

	/**
	 * 修改权限
	 */
	@Transactional
	@Override
	public int update(UpdateSysPermissionReqParam param,String name) {
		SysPermission bean = sysPermissionMapper.selectById(param.getId());
		if (bean == null) {
			throw new MsgException(CodeEnum.SYS_PERMISSION_ERROR);
		}
		int count = sysPermissionMapper.selectByPerCode(param.getPerCode());
		if (count > 0) {
			if (!bean.getPerCode().equals(param.getPerCode())) {
				throw new MsgException(CodeEnum.SYS_PERMISSION_CODE_ERROR);
			}
		}
		msgException(param.getPerCode(),param.getPerName(),param.getPerType(), param.getItsApplicationCode(), param.getSort());
		BeanUtils.copyProperties(param, bean);
		bean.setCreateby(name);
		bean.setSort(Integer.parseInt(param.getSort()));
		int num = sysPermissionMapper.updateById(bean);
		return num;
	}
	
	/**
	 * 抽取增加修改公共异常
	 * @param type
	 * @param itsApplicationCode
	 * @param sort
	 */
	public void msgException(String perCode,String perName,String type,String itsApplicationCode,String sort) {
		if(StringUtils.isEmpty(perCode)) {
			throw new MsgException(CodeEnum.SYS_PERMISSION_PERCODE_ERROR);
		}
		if(StringUtils.isEmpty(perName)) {
			throw new MsgException(CodeEnum.SYS_PERMISSION_PERNAME_ERROR);
		}
		if(StringUtils.isEmpty(type)) {
			throw new MsgException(CodeEnum.SYS_PERMISSION_TYPE_ERROR);
		}
		if(StringUtils.isEmpty(itsApplicationCode)) {
			throw new MsgException(CodeEnum.SYS_PERMISSION_APP_ERROR);
		}
		if(StringUtils.isEmpty(sort)) {
			throw new MsgException(CodeEnum.SYS_PERMISSION_SORT_ERROR);
		}
	}

	/**
	 * 禁用启用菜单(权限)
	 */
	@Transactional
	@Override
	public int enable(EnableSysPermissionReqParam param) {
		SysPermission bean=sysPermissionMapper.selectById(param.getId());
		if(null==bean) {
			throw new MsgException(CodeEnum.SYS_PERMISSION_ERROR);
		}
		String isVaild=bean.getIsVaild();
		if(isVaild.equals(IsDisableEnum.NO.getKey()+"")) {
			// YES(1,"已禁用") NO(0,"未禁用")
			bean.setIsVaild(IsDisableEnum.YES.getKey()+"");
		}else {
			bean.setIsVaild(IsDisableEnum.NO.getKey()+"");
		}
		//修改自己
		int upd=sysPermissionMapper.updateById(bean);
		//查询子级
		QueryWrapper<SysPermission>queryWrapper=new QueryWrapper<>();
		queryWrapper.eq("parent_code", bean.getPerCode());
		List<SysPermission>list=sysPermissionMapper.selectList(queryWrapper);
		for (int i = 0; i < list.size(); i++) {
			String perCode=list.get(i).getPerCode();
			//递归修改子级
			recursion(perCode, bean.getIsVaild());
		}
		return upd;
	}
	/**
	 * 递归修改菜单(权限)状态
	 * @param perCode
	 * @param isVaild
	 * @return
	 */
	@Transactional
	public int recursion(String perCode,String isVaild) {
		//先修改自己 在修改子级
		int num=sysPermissionMapper.updateSysPermissionByPerCode(isVaild,perCode);
		//查询子级
		QueryWrapper<SysPermission>queryWrapper=new QueryWrapper<>();
		queryWrapper.eq("parent_code", perCode);
		List<SysPermission>list=sysPermissionMapper.selectList(queryWrapper);
		for (int i = 0; i < list.size(); i++) {
			String per_code=list.get(i).getPerCode();
			sysPermissionMapper.updateSysPermissionByPerCode(isVaild,perCode);
			//递归修改子级
			recursion(per_code, isVaild);
		}
		return 1;
	}

	/**
	 * 查询菜单权限树
	 */
	@Override
	public JSONArray querySysPermissionTree(String perName, String itsApplicationCode) {
		
		List<SysPermissionDto> list=sysPermissionMapper.selectSysPermissionTree(perName,itsApplicationCode);
		list.forEach(x->{
			String is_enable=x.getIsVaild();
			if(is_enable.equals(IsDisableEnum.NO.getKey()+"")) {
				is_enable=IsDisableEnum.NO.getValue()+"";
			}else {
				is_enable=IsDisableEnum.YES.getValue()+"";
			}
			x.setIsVaild(is_enable);
		});
		List<SysPermissionDto> listTree=buildTree(list,"");
		JSONArray trssJson= JSONArray.parseArray(JSON.toJSONString(listTree));
		return trssJson;
	}
	
	/**
	 * 递归子节点
	 * @param list
	 * @param parentId
	 * @return
	 */
	public static List<SysPermissionDto> buildTree(List<SysPermissionDto> list,String parentId){
		List<SysPermissionDto> menus=new ArrayList<SysPermissionDto>();
	    for (SysPermissionDto menu : list) {  
	    	  //本身id
	          String menuId = menu.getPerCode();
	          //父id
	          String pid = menu.getParentCode();
	          if (parentId.equals(pid)) {  
	              List<SysPermissionDto> menuLists = buildTree(list, menuId);  
	              menu.setChildMenu(menuLists);
	              menus.add(menu);  
	          }  
	    }  
		return menus;
	}
}
